from django.db import models

from tracadmin import scripts

class Repository(models.Model):
    title = models.CharField(max_length=250)
    slug = models.SlugField(unique=True)
    description = models.TextField(blank=True)

    class Meta:
        verbose_name_plural = u'Repositories'

    def save(self):
        super(Repository,self).save()
        scripts.save_repository(self)

    def delete(self):
        super(Repository,self).delete()
        scripts.delete_repository(self)

    def __unicode__(self):
        return self.title


PERM_CHOICES = (
    (' ', 'None'),  # We use a space to avoid triggering Django's blank string detector.
    ('r', 'Read'),
    ('w', 'Write'),
    ('rw', 'Read and Write'),
    )

class EntityList(object):
    '''Represents a list of all users and groups, including special
    entities designating all users (including anonymous users) and
    all authenticated users.'''

    _extras = (
        ('*', '[All users]'),
        ('@allusers', '[Authenticated users]')
    )

    def __iter__(self):
        from django.contrib.auth.models import User, Group
        from django.template.defaultfilters import slugify
        from itertools import chain
        users = ((user.username, "User: " + user.username) for user in User.objects.all())
        groups = (("@" + slugify(group.name), "Group: " + group.name) for group in Group.objects.all())
        return chain(self._extras,users,groups)


class SVNPerm(models.Model):
    repo = models.ForeignKey(Repository)
    directory = models.CharField(max_length=1024)
    entity = models.CharField(max_length=32, choices=EntityList())
    perms = models.CharField("Permissions", max_length=4, choices=PERM_CHOICES, default=' ')

    class Meta:
        verbose_name = 'SVN Permission'
        ordering = ('repo', 'directory')

    def save(self):
        super(SVNPerm,self).save()
        scripts.sync_svn_access_file(SVNPerm.objects.all())

    def delete(self):
        super(SVNPerm,self).delete()
        scripts.sync_svn_access_file(SVNPerm.objects.all())

    def __unicode__(self):
        return u'Permissions for ' + self.entity + u' to ' + self.repo.slug + u':' + self.directory
